package com.projects.android.views;

import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.projects.android.R;
import com.projects.android.bus.MenuBUS;
import com.projects.android.bus.OrderDetailBUS;
import com.projects.android.bus.OrdersBUS;
import com.projects.android.dto.FoodDTO;
import com.projects.android.dto.MenuDTO;
import com.projects.android.dto.OrderDetailDTO;
import com.projects.android.dto.OrdersDTO;
import com.projects.android.utils.SelectedItems;
import com.projects.android.utils.Utils;

public class CheckoutInfo extends Activity implements OnClickListener {
	private Button btnOK;

	private EditText txtReceiverName;
	private EditText txtReceiverPhone;
	private EditText txtReceiverAddress;
	private EditText txtDeliveryNote;
	private Intent intent;
	
	// Use an existing ListAdapter that will map an array
	// of strings to TextViews
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.checkoutinfo);
		initFrm();
	}

	private void initFrm() {
		btnOK = (Button) findViewById(R.id.btnCheckout_OK);

		txtReceiverName = (EditText) findViewById(R.id.txtCheckout_ReceiverName);
		txtReceiverPhone = (EditText) findViewById(R.id.txtCheckout_ReceiverPhone);
		txtReceiverAddress = (EditText) findViewById(R.id.txtCheckout_ReceiverAddress);
		txtDeliveryNote = (EditText) findViewById(R.id.txtCheckout_DeliveryNote);

		txtReceiverName.setText(SelectedItems.SelectedUsers.getName());
		txtReceiverPhone.setText(SelectedItems.SelectedUsers.getPhone());
		txtReceiverAddress.setText(SelectedItems.SelectedUsers.getAddress());
		
		btnOK.setOnClickListener(this);
	}

	private boolean checkOut(){
		// Create a new order
		OrdersDTO newOrder = new OrdersDTO();
		newOrder.setIDRestaurant(SelectedItems.SelectedRestaurant.getID());
		Log.i("Checkout SelectedRestaurant", String.valueOf(newOrder.getIDRestaurant()));
		newOrder.setIDUsers(SelectedItems.SelectedUsers.getID());
		newOrder.setOrderDate(Utils.DATE_FORMATTER.format(new Date()));
		newOrder.setDeliveryNote(txtDeliveryNote.getText().toString());
		newOrder.setReceiverName(txtReceiverName.getText().toString());
		newOrder.setReceiverPhone(txtReceiverPhone.getText().toString());
		newOrder.setReceiverAddress(txtReceiverAddress.getText().toString());
		int idOrder;
		boolean result = false;
		if ((idOrder = OrdersBUS.insert(newOrder)) != -1) {
			// Create new order details
			for (FoodDTO food : SelectedItems.SelectedFoods) {
				OrderDetailDTO orderDetail = new OrderDetailDTO();
				orderDetail.setIDOrder(idOrder);
				orderDetail.setIDFood(food.getID());
				orderDetail.setPrice(food.getPrice());
				orderDetail.setQuantity(food.getQuantity());
				OrderDetailBUS.insert(orderDetail);
			}
			
			result = true;
			
			// Remove all selected items
			SelectedItems.SelectedFoods.clear();
			// Update list all foods
			SelectedItems.AllFoods.clear();
			ArrayList<MenuDTO> arrMenus = MenuBUS
					.selectByIDRestaurant(SelectedItems.SelectedRestaurant
							.getID());
			for (MenuDTO menu : arrMenus) {
				ArrayList<FoodDTO> foods = menu.getFoods();
				for (FoodDTO food : foods) {
					// Set menu name for each food item
					food.setMenuName(menu.getName());
					SelectedItems.AllFoods.add(food);
				}
			}
		}
		return result;
	}
	
	public void processCheckout(){
		final ProgressDialog dialog = new ProgressDialog(this);
		dialog.setTitle("Loading. Please wait...");
		dialog.setIndeterminate(true);
		
		final Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				runOnUiThread(new Runnable() {
					final boolean result = checkOut();
					@Override
					public void run() {
						Menu.MenuView.loadData();
						Cart.CartView.loadData();
						
						// Invisible progress dialog
						dialog.dismiss();
						
						if(result){
							if(ManageOrders.Instance != null){
								ManageOrders.Instance.loadData();
							}
							AlertDialog dlg = new AlertDialog.Builder(CheckoutInfo.this).setTitle("Information").setMessage("Order is checked out, we will contact with you as soon as possible")
									.setPositiveButton("OK", new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog, int whichButton) {
											intent = Utils.browseIntent(CheckoutInfo.this, "Main");
											startActivity(intent);
										}
									}).create();
									dlg.show();		
						}else{
							AlertDialog dlg = Utils.showAlertDlg(CheckoutInfo.this,
									"Information", "Cannot checkout order");
							dlg.show();
						}
					}
				});
			}
		});
		dialog.show();
		thread.start();
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnCheckout_OK:
			if (!ValidateCheckout()) {
				return;
			}
			processCheckout();
			break;
		}
	}

	public boolean ValidateCheckout() {
		String errorTxt = "";
		if (txtReceiverName.getText().toString().equals("")) {
			errorTxt = "Receiver's name is empty";
		} else if (txtReceiverPhone.getText().toString().equals("")) {
			errorTxt = "Receiver's phone is empty";
		} else if (txtReceiverAddress.getText().toString().equals("")) {
			errorTxt = "Receiver's address is empty";
		} 
		if (!errorTxt.equals("")) {
			AlertDialog dlg = Utils.showAlertDlg(this, "Validate Checkout",
					errorTxt);
			dlg.show();
			return false;
		}
		return true;
	}
}
